﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NetAssist.IO;

namespace NetAssistTests
{
  [DeploymentItem("Resources\\IMG_2824.JPG")]
  [TestClass()]
  public class BinaryFileTests
  {
    private const int READ_SIZE = 2048;

    [TestMethod()]
    public void BinaryFileTest1()
    {
      string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
      path = Path.Combine(path, "IMG_2824.JPG");

      byte[] content1 = new byte[139479];
      byte[] content2 = new byte[139479];

      IEnumerable<BinaryFileBlock> BinaryFileReader = BinaryFile.ReadFile(path, READ_SIZE);
      foreach (BinaryFileBlock block in BinaryFileReader)
        Array.Copy(block, 0, content1, block.StartPosition, block.Length);

      File.OpenRead(path).Read(content2, 0, content2.Length);
      Assert.IsTrue(content1.SequenceEqual(content2));
      Assert.IsTrue(BinaryFileReader.First().BlockIndex == 0);

      BinaryFileBlock lastBlock = BinaryFileReader.Last();

      Assert.IsTrue(lastBlock.BlockIndex == 68);
      Assert.IsTrue(lastBlock.EndPosition == 139478);
      Assert.IsTrue(lastBlock.Length == 215);
      Assert.IsTrue(lastBlock.StartPosition == 139264);
      Assert.IsTrue(lastBlock.StartPosition / lastBlock.BlockIndex == READ_SIZE);

      Assert.IsTrue(content2.Skip(lastBlock.StartPosition).SequenceEqual(BinaryFileBlock.FromBinaryFileBlock(lastBlock)));
    }

    [TestMethod()]
    public void BinaryFileTest2()
    {
      string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
      path = Path.Combine(path, "IMG_2824.JPG");

      IEnumerable<BinaryFileBlock> bfr1 = BinaryFile.ReadFile(path, BinReader);
      IEnumerable<BinaryFileBlock> bfr2 = BinaryFile.ReadFile(path, READ_SIZE);

      byte[] block1 = bfr1.Skip(3).First();
      byte[] block2 = bfr2.Skip(3).First();
      Assert.IsTrue(block1.SequenceEqual( block2));
    }

    private byte[] BinReader(Stream source)
    {
      byte[] arr = new byte[READ_SIZE];
      source.Read(arr, 0, READ_SIZE);
      return arr;
    }
  }
}
